package com.easy.leetcode;

/**
 * 58. 最后一个单词的长度
 */
public class LengthOfLastWord58 {
    public int lengthOfLastWord(String s) {
        s=s.trim();
        String[] arrs= s.split(" ");
        return arrs[arrs.length-1].length();
    }
    public static int lengthOfLastWord1(String s) {
        char[] arr= s.toCharArray();
        StringBuffer sb = new StringBuffer();
        Character pre =null;
        for (char c : arr) {
            if (!Character.isSpaceChar(c)) {
                if (pre!=null&&Character.isSpaceChar(pre)){
                    sb= new StringBuffer();
                }
                sb.append(c);
            }
            pre=c;
        }
        return sb.length();
    }
    public static int lengthOfLastWord2(String s) {
        char[] arr= s.toCharArray();
        StringBuffer sb = new StringBuffer();
        Character pre =null;
        int len=arr.length-1;
        int wlen=0;
        for (int i = len; i >=0; i--) {
            if (!Character.isSpaceChar(arr[i])) {
                wlen++;
            }else {
                if (pre!=null&&pre!=' '){
                    return wlen;
                }
            }
            pre=arr[i];
        }
        return wlen;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLastWord2("Hello World"));
    }
}
